using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace Zsa.Emulation.Util
{
    [StructLayout(LayoutKind.Sequential)]
    public struct MSG {
	    public IntPtr hWnd;
	    public int msg;
	    public IntPtr wParam;
	    public IntPtr lParam;
	    public uint time;

	    public System.Drawing.Point p;
    }

    public static class PeekMessage 
    {
        /// <summary>
        /// Gets a value indicating whether this instance has message.
        /// </summary>
        /// <value>
        /// 	<c>true</c> if this instance has message; otherwise, <c>false</c>.
        /// </value>
        public static bool HasMessage
        {
            get
            {
                MSG _Msg = new MSG();
                return InternalPeekMessage(out _Msg, IntPtr.Zero, 0, 0, PeekMessageOption.PM_NOREMOVE);
            }
        }

        public static void Run()
        {
            MSG msg = new MSG();
            while (InternalPeekMessage(out msg, IntPtr.Zero, 0, 0, PeekMessageOption.PM_REMOVE))
            {
                if (msg.msg == WM_QUIT)
                    break;

                TranslateMessage(ref msg);
                DispatchMessage(ref msg);
            }
        }




        [DllImport("user32.dll", SetLastError = true)]
        private static extern bool TranslateMessage(ref MSG lpMsg);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern Int32 DispatchMessage(ref MSG lpMsg);

        private enum PeekMessageOption : uint
        {
            PM_NOREMOVE = 0,
            PM_REMOVE
        }

        private static Int32 WM_QUIT = 0x12;


        [System.Security.SuppressUnmanagedCodeSecurity] // This prevents run-time security checks, so DON'T LEAVE THIS SOMEWHERE INSECURE
        [DllImport("User32.dll", CharSet=CharSet.Auto, EntryPoint="PeekMessage")]
        private static extern bool InternalPeekMessage(out MSG msg, IntPtr hWnd, uint messageFilterMin, uint messageFilterMax, PeekMessageOption flags);
    }
	
}
